package dxn.nl.export.deal.export;

import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.util.MapUtils;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.style.column.AbstractColumnWidthStyleStrategy;
import dxn.nl.file.client.model.dto.CsExportExcelHeadDto;
import org.apache.poi.ss.usermodel.Cell;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class CusColumnWidthStyleStrategy extends AbstractColumnWidthStyleStrategy {
    private static final int MAX_COLUMN_WIDTH = 255;
    private final Map<Integer, Map<Integer, Integer>> cache = MapUtils.newHashMapWithExpectedSize(8);
    private final CsExportExcelHeadDto[] heads;

    public CusColumnWidthStyleStrategy(CsExportExcelHeadDto[] headDtos) {
        this.heads = headDtos;
    }

    public CusColumnWidthStyleStrategy(List<CsExportExcelHeadDto> headList) {
        this.heads = new CsExportExcelHeadDto[headList.size()];
        headList.toArray(heads);
    }

    protected void setColumnWidth(WriteSheetHolder writeSheetHolder, List<WriteCellData<?>> cellDataList, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {
        if(!isHead)
        {
            return;
        }
        Map<Integer, Integer> maxColumnWidthMap = this.cache.computeIfAbsent(writeSheetHolder.getSheetNo(), (key) -> new HashMap(16));

        int columnIndex = cell.getColumnIndex();
        int dataLength = cell.getStringCellValue().getBytes().length;

        if(heads != null && heads.length>0)
        {
            if(columnIndex >= heads.length)
            {
                return ;
            }

            CsExportExcelHeadDto headDto = heads[columnIndex];

            if(dataLength < headDto.getColumnLength())
            {
                dataLength = headDto.getColumnLength();
            }
        }

        if (dataLength > MAX_COLUMN_WIDTH) {
            dataLength = MAX_COLUMN_WIDTH;
        }

        maxColumnWidthMap.put(cell.getColumnIndex(), dataLength);
        writeSheetHolder.getSheet().setColumnWidth(cell.getColumnIndex(), dataLength * 256);
    }
}
